/**
 * Copyright 2024-2024 Huawei Technologies Co., Ltd
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#include "ndk_util.h"

#include <dlfcn.h>

#include "framework/infra/log/log.h"
#include "infra/base/so_path.h"

namespace hiai {
HIAI_DDKPipe NDKUtil::ddkPipe_ = HIAI_DDK_PIPE_UNSET;

namespace {
bool CanOpenSo(const char* soPath)
{
    void* handle = dlopen(soPath, RTLD_LAZY);
    if (handle == nullptr) {
        FMK_LOGW("dlopen [%s] failed", soPath);
        return false;
    }
    dlclose(handle);
    FMK_LOGI("dlopen [%s] success", soPath);
    return true;
}
}

bool NDKUtil::CanDlopenVendorSo()
{
    if (ddkPipe_ != HIAI_DDK_PIPE_UNSET) {
        return ddkPipe_ == HIAI_DDK_PIPE_VENDOR;
    }

    const char* vendorPath = SO_PATH_PREFIX"libai_fmk_hcl_model_runtime.so";
    if (CanOpenSo(vendorPath)) {
        ddkPipe_ = HIAI_DDK_PIPE_VENDOR;
        FMK_LOGI("ddkPipe is vendor");
        return true;
    }
    FMK_LOGI("ddkPipe is ndk");
    ddkPipe_ = HIAI_DDK_PIPE_NDK;
    return false;
}

}